﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Text;
using System.Data;
using DevExpress.Web.ASPxGridView;
using GPSTracker.Views.DAL;
using GPSTracker.Helper;
using System.Xml;
using System.Data.SqlClient;

namespace GPSTracker.Views.Master
{
    public partial class Product : System.Web.UI.Page
    {
        private ProductDAL objProductDAL = new ProductDAL();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void BindGridview()
        {
            try
            {
                grdView.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                ClearPopUpCntrls(false);
                lblMessage.Visible = false;
                btnSave.Visible = true;
                btnUpdate.Visible = false;
                popup.ShowOnPageLoad = true;
                txtProductCode.Focus();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                BindGridview();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void grdView_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            try
            {
                var grid = (ASPxGridView)sender;
                var keyValue = grid.GetRowValues(e.VisibleIndex, "ProductID").ToString();
                hdnProductID.Value = keyValue;

                if (e.ButtonID == "btnEdit")
                {
                    txtProductCode.Focus();
                    btnUpdate.Visible = true;
                    btnSave.Visible = false;
                    lblMessage.Visible = false;
                    lblMessage.Text = string.Empty;
                    ClearPopUpCntrls(true);
                    popup.ShowOnPageLoad = true;

                    var dt = new DataTable();
                    dt = objProductDAL.FillProductMasterGrid(keyValue);
                    if (dt.Rows.Count > 0)
                    {
                        txtProductCode.Text = dt.Rows[0]["ProductCode"].ToString();
                        txtProductName.Text = dt.Rows[0]["ProductName"].ToString();
                        txtProductDescription.Text = dt.Rows[0]["ProductDesc"].ToString();

                        if (dt.Rows[0]["IsActive"].ToString() == "True")
                        {
                            chkIsActive.Checked = true;
                        }
                        else
                        {
                            chkIsActive.Checked = false;
                        }
                    }
                }
                else
                {
                    if (e.ButtonID == "btnDelete")
                    {
                        objProductDAL.DeleteProductMaster(keyValue);
                        BindGridview();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveData(false);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            SaveData(true);
        }

        private bool SaveData(bool IsModify)
        {
            var settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.Entitize;
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new StringBuilder();

            try
            {
                var CmdSave = new SqlCommand();
                CmdSave.Connection = CommonFx.GetSqlCon();
                CmdSave.CommandType = CommandType.StoredProcedure;
                CmdSave.CommandText = "SP_InsertProductMaster";

                using (var xw = XmlWriter.Create(sb, settings))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("CS");
                    xw.WriteStartElement("ProductMaster");
                    if (IsModify == true)
                    {
                        xw.WriteElementString("ProductID", hdnProductID.Value);
                    }
                    xw.WriteElementString("ProductCode", txtProductCode.Text.Trim());
                    xw.WriteElementString("ProductName", txtProductName.Text.Trim());
                    xw.WriteElementString("ProductDesc", txtProductDescription.Text.Trim());
                    if (chkIsActive.Checked == true)
                    {
                        xw.WriteElementString("IsActive", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsActive", "0");
                    }
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    xw.WriteElementString("CreatedBy", lg.LoginID.ToString());
                    xw.WriteElementString("ModifiedBy", lg.LoginID.ToString());
                    xw.WriteEndElement();
                    xw.WriteEndDocument();
                    xw.Close();
                }
                CmdSave.Parameters.Add(new SqlParameter("@pXML", sb.ToString()));
                if (IsModify == false)
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", false));
                }
                else
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", true));
                }

                CmdSave.Parameters.Add("@pIsErrorFound", SqlDbType.Bit);
                CmdSave.Parameters.Add("@pErrorMessage", SqlDbType.NVarChar, 4000);
                CmdSave.Parameters.Add("@pCustomerID", SqlDbType.Int);

                CmdSave.Parameters["@pIsErrorFound"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pErrorMessage"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pCustomerID"].Direction = ParameterDirection.Output;

                CmdSave.ExecuteNonQuery();
                var strError = string.Empty;
                var str = CmdSave.Parameters["@pIsErrorFound"].Value.ToString();
                if (!Convert.ToBoolean(CmdSave.Parameters["@pIsErrorFound"].Value))
                {
                    if (IsModify == false)
                    {
                        strError = string.Empty;
                        lblMessage.Visible = true;
                        lblMessage.Text = "Branch Inserted Successfully.";
                        ScriptManager.RegisterStartupScript(UpMain, typeof(Page), "message", "Fade('" + lblMessage.ClientID + "');", true);
                        ClearPopUpCntrls(false);
                        txtProductCode.Focus();
                    }
                    else
                    {
                        strError = string.Empty;
                        lblMessage.Visible = true;
                        lblMessage.Text = "Branch Updated Successfully.";
                        ScriptManager.RegisterStartupScript(UpMain, typeof(Page), "message", "Fade('" + lblMessage.ClientID + "');", true);
                        txtProductCode.Focus();
                    }

                    return true;
                }
                else
                {
                    if (IsModify == false)
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                        btnSave.Visible = true;
                    }
                    else
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                        btnUpdate.Visible = true;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ClearPopUpCntrls(bool IsEditMode)
        {
            txtProductCode.Text = string.Empty;
            txtProductDescription.Text = string.Empty;
            txtProductName.Text = string.Empty;
            chkIsActive.Checked = false;
        }
    }
}
